<?php


namespace app\api\controller;


use addons\epay\library\Service;
use app\common\controller\Api;
use app\common\controller\Util;
use app\common\library\Sms;
use Endroid\QrCode\QrCode;
use think\Db;
use think\Env;
use think\Exception;
use think\Hook;
use think\Response;
use Yansongda\Pay\Pay;

class Bizcommon extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['Test', 'wechatNotifyx', 'myAdList','aliNotifyx', 'getCourseLesson', 'addoneByone', 'qrcode', 'getNoobInfo', 'gradeList', 'subjectList', 'tagList', 'courseList', 'protocols', 'getCourseById', 'getCourseOutline', 'wechatNotifyxFund', 'cityInfo', 'myList', 'classList'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
    }

    public function Test()
    {
        $notifyurl = $this->request->root(true) . '/api/Bizcommon/wechatNotifyx';
//       $res =  Service::submitOrder('0.01','2132121211','wechat','测试',$notifyurl,'','scan');
//       dump($res);
//        $res = Util::weChatRefund('BJ902149986161772', 'BJ902149986161772', '1', '1', '测试', $this->request->root(true) . '/api/Bizcommon/wechatNotifyx');
//        dump($res);
//        $param = $this->request->post();
    }

    /**
     * Notes:回调接值
     * User: XingLiangRen
     * Date: 2020/8/28
     * Time: 11:30
     */
    public function wechatNotifyx()
    {
        $result = [];
        $type = $this->request->param('type');
        if ($type == 'wechat') {
            $testxml = file_get_contents("php://input");
            // 接受微信回调数据
            $result = Util::xmlToArray($testxml);
            // 将xml数据转为数组
            Util::write_log(json_encode($result, JSON_UNESCAPED_UNICODE));
        } elseif ($type == 'alipay') {
            Util::write_log(input());
            $result = input();
        }

        // 处理逻辑
        $order_sn = $result['out_trade_no'];
        $order = Db::name('order')->where('batch_id', $order_sn)->select();
//            交易订单是否锁定
        Db::startTrans();
        try {
            $res = Db::name('order')->where('batch_id', $order_sn)->update(array('status' => 'paid', 'paid_time' => Util::getNowDateTime()));
            Util::write_log(json_encode($res, JSON_UNESCAPED_UNICODE));
            $res1 = Db::name('cash_flow')->where('batch_id', $order_sn)->setField('status', '1');
            Util::write_log(json_encode($res1, JSON_UNESCAPED_UNICODE));
            foreach ($order as $key => $value) {
                if ($key === 0) {
                    Db::name('course')->where('id', $value['courseId'])->setInc('student_num', 1);
                }
                if ($value['coupon_id']) {
                    Db::name('coupon_user')->where('coupon_id', $order['coupon_id'])->setField('status', '3');
                }
//                    支付回调分销处理
                $hooks_data = [
                    'orderID' => $value['id'],
                ];
                Hook::listen("commonDistribution", $hooks_data);
            }
            Db::commit();
            //你可以在这里你的业务处理逻辑,比如处理你的订单状态、给会员加余额等等功能
            //下面这句必须要执行,且在此之前不能有任何输出
            echo "success";
            return;
//            Util::wechatSuccess();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            Util::write_log(json_encode($e->getMessage(), JSON_UNESCAPED_UNICODE));
        }
//        $bizorder = new Bizorder();
//        $bizorder->payNotify($out_trade_no);
        // 告知微信接受回调成功
    }

    /**
     * 支付成功回调
     */
    public function aliNotifyx()
    {
        $type = $this->request->param('type');
        $data = $this->request->request('', null, 'trim');
        $config = Service::getConfig($type);
        $pay = new Pay($config);
        if (!$pay->driver($type)->gateway()->verify($data)) {
            echo '签名错误';
            return;
        }
        $res = $pay->verify();
        Util::write_log(\GuzzleHttp\json_encode($res, JSON_UNESCAPED_UNICODE));
        //你可以在这里你的业务处理逻辑,比如处理你的订单状态、给会员加余额等等功能
        //下面这句必须要执行,且在此之前不能有任何输出
        echo "success";
        return;
    }

    /**
     * @Notes:
     * @Author: zhao
     * @Date: 2020/9/1
     * @Time: 10:18
     * @Interface wechatNotifyxFund
     * 退款回调
     */
    public function wechatNotifyxFund()
    {
        // 接受微信回调数据
        $testxml = file_get_contents("php://input");
        // 将xml数据转为数组
        $result = Util::xmlToArray($testxml);
        // 处理逻辑
        $out_trade_no = $result['out_trade_no'];
        $bizorder = new Bizorder();
        $bizorder->refundBack($out_trade_no);
        Util::write_log(json_encode($result, JSON_UNESCAPED_UNICODE));
        // 告知微信接受回调成功
        Util::wechatSuccess();
    }

    /**
     * 生成二维码
     * @return Response
     */
    public function qrcode()
    {
        $code = $this->request->get('code', 'hello world');
        $text = Env::get('app.baseUrl') . "/login?code=" . $code;
        $size = $this->request->get('size', 250);
        $padding = $this->request->get('padding', 15);
        $errorcorrection = $this->request->get('errorcorrection', 'medium');
        $foreground = $this->request->get('foreground', "#ffffff");
        $background = $this->request->get('background', "#000000");
        $logo = $this->request->get('logo');
        $logosize = $this->request->get('logosize');
        $label = $this->request->get('label');
        $labelfontsize = $this->request->get('labelfontsize');
        $labelhalign = $this->request->get('labelhalign');
        $labelvalign = $this->request->get('labelvalign');

        // 前景色
        list($r, $g, $b) = sscanf($foreground, "#%02x%02x%02x");
        $foregroundcolor = ['r' => $r, 'g' => $g, 'b' => $b];

        // 背景色
        list($r, $g, $b) = sscanf($background, "#%02x%02x%02x");
        $backgroundcolor = ['r' => $r, 'g' => $g, 'b' => $b];

        $qrCode = new QrCode();
        $qrCode
            ->setText($text)
            ->setSize($size)
            ->setPadding($padding)
            ->setErrorCorrection($errorcorrection)
            ->setForegroundColor($foregroundcolor)
            ->setBackgroundColor($backgroundcolor)
            ->setLogoSize($logosize)
            ->setLabelFontPath(ROOT_PATH . 'public/assets/fonts/Times New Roman.ttf')
            ->setLabel($label)
            ->setLabelFontSize($labelfontsize)
            ->setLabelHalign($labelhalign)
            ->setLabelValign($labelvalign)
            ->setImageType(QrCode::IMAGE_TYPE_PNG);
        //也可以直接使用render方法输出结果
        //$qrCode->render();
        return new Response($qrCode->get(), 200, ['Content-Type' => $qrCode->getContentType()]);
    }

    /**
     * Notes:年级列表
     * User: XingLiangRen
     * Date: 2020/8/14
     * Time: 16:27
     * 年級列表
     */
    public function gradeList()
    {
        $List = Db::name("grade")->order("weigh ASC")->select();
        $this->success("查询成功", $List);
    }

    /**
     * Notes:科目列表
     * User: XingLiangRen
     * Date: 2020/8/17
     * Time: 16:11
     */
    public function subjectList()
    {
        $grade_id = $this->request->get('grade_id');
        $subjectList = Db::name('subject')->field('id,subject_name,image,create_time')->select();
        if (Util::checkEmpty($grade_id)) {
            $subjectList = Db::query("select id,subject_name,image,create_time from `by_subject` where FIND_IN_SET($grade_id,grade_ids)");
        }
        $this->success("查询成功", $subjectList);
    }

    /**
     * Notes:标签列表
     * User: XingLiangRen
     * Date: 2020/8/17
     * Time: 17:30
     */
    public function tagList()
    {
        $data = Db::name('tag')->field(['id', 'tag_name', 'create_time', 'pid'])->select();
        $this->success("查询成功", array_values(Util::getTree($data, 0)));
    }

    /**
     * Notes:课程列表
     * User: XingLiangRen
     * Date: 2020/8/20
     * Time: 13:46
     */
    public function courseList()
    {
        //标签
        $tag_ids = $this->request->get("tag_ids");
        //年级
        $grade_id = $this->request->get( "grade_id");
        //学科
        $subject_id = $this->request->get("subject_id");
        //type_status 公开课等
        $type_status = $this->request->get("type_status");
        //classify_type  课程类型
        $classify_type = $this->request->get("classify_type");
        //标题模糊搜索
        $title = $this->request->get("title");
        // 类型 1= 前三类似搜索 2= 不进行递归子集分类
        $search_type = $this->request->get('search_type', 0);
        $course_id = $this->request->get("course_id");
        $order = ['c.classify_type' => 'ASC', 'c.id' => 'desc'];
        $offect = 0;
        $limit = 0;
        $where = "is_check = '2' AND is_issue = '1' AND  is_apply = '1' ";
        if (Util::checkEmpty($course_id) && $search_type === '1') {
            $order = ['hit_num' => 'desc'];
            $limit = 3;
            $where .= " AND c.id != $course_id ";
        }
        if ($search_type === '3') {
            $order = ['hit_num' => 'desc'];
            $limit = 3;
        }
        if (!empty($tag_ids)) {
            $where .= " AND (";
            $ids = explode(",", $tag_ids);
            foreach ($ids as $k => $v) {
                $where .= " FIND_IN_SET($v,tag_ids)";
                if (count($ids) - 1 != $k) {
                    $where .= " OR ";
                }
            }
            $where .= ") ";
        }
        $where .= Util::checkEmpty($grade_id) ? " AND grade_id = $grade_id" : '';
        $where .= Util::checkEmpty($subject_id) ? " AND subject_id = $subject_id" : '';
        $where .= Util::checkEmpty($type_status) ? " AND type_status = $type_status" : '';
        $where .= Util::checkEmpty($classify_type) ? " AND classify_type = $classify_type" : '';
        $where .= Util::checkEmpty($title) ? " AND title like '%$title%'" : '';
        $data = Db::name('course')->alias('c')->where($where)
            ->join("teacher t", "c.teacher_id = t.id", 'LEFT')
            ->join("classify cl", "c.classify_type = cl.id", 'LEFT')
            ->join('helper h', "c.help_id = h.id", 'LEFT')
            ->field(['classify_type', 'eng_name', 'h.id as help_id', 'h.header as helper_header', 'cl.name as classifyName', 'c.id', 'title', 'subtitle', 'cover_image', 'tache', 'duration',
                'teacher_manifesto', 'difficulty', 'is_free', 'price',
                'is_promotion', 'is_discount', 'section_num','discount', 'discount_indate', 'c.type_status', 'c.course_num', 'c.student_num', 'promotion_price', 't.name', 't.header', 'grade_id', 'subject_id'])
            ->order($order)
            ->limit($offect, $limit)
            ->select();
        $newData = $data;
        if ($search_type != 2 && !Util::checkEmpty($course_id)) {
            $newData = array_flip(array_column($data, 'eng_name'));
            foreach ($data as $k => $v) {
                if (Util::checkEmpty($newData[$v['eng_name']], 'array')) {
                    array_push($newData[$v['eng_name']]['child'], $v);
                } else {
                    $newData[$v['eng_name']] = [
                        'classify_type' => $v['classify_type'],
                        'classifyName' => $v['classifyName'],
                        'child' => [$v]
                    ];
                }
            }
        }
        $this->success('查询成功', array_values($newData));
    }

    public function getCourseById()
    {
        $id = $this->request->param('id');
        if (!Util::checkEmpty($id)) {
            $this->error("缺少参数");
        }
        $data = Db::name('course')->alias('c')
            ->join('teacher t', 'c.teacher_id = t.id')
            ->where('c.id', $id)
            ->field(['c.id', 'c.title', 'c.subtitle', 'c.cover_image',
                'price', 'content', 'c.difficulty', 'c.promotion_price',
                'c.section_num', 'expiry_start_time', 'expiry_end_time', 'c.type_status',
                'c.is_promotion', 'is_discount', 'discount', 'discount_indate', 'c.course_num', 'c.student_num', 'c.trial_video', 'c.is_trail', 't.nick_name as name', 't.header'])
            ->find();
        Db::name('course')->where('id', $id)->setInc('hit_num');
        $userId = $this->getUid();
        if (!empty($userId)) {
            $data['discountStatus'] = 4;
            $ret = Db::name('coupon_user')->where(['uid' => $userId, 'course_id' => $id])->find();
            if ($ret) {
                $data['discountStatus'] = $ret['status'];
            }
        }
        $this->success('查询成功', $data ?? []);
    }

    /**
     * Notes:1to1表单
     * User: XingLiangRen
     * Date: 2020/9/9
     * Time: 14:28
     */
    public function addoneByone()
    {
        $param = $this->request->post();
        // 数据校验START
        $data = $this->validate($param, [
            'phone' => 'require|regex:/^1[3456789]\d{9}$/',
            'code' => 'require|regex:/^\d{6}$/i',
        ], [
                'phone.require' => '手机号码必填',
                'phone.regex' => '手机号码格式错误',
                'code.require' => '短信验证码为必填',
                'code.regex' => '短信验证码格式错误',
            ]
        );
        if (!empty($data) && $data !== true) {
            return $this->error($data);
        }
        // 验证验证码的正确
        $smsResult = Sms::check($param['phone'], $param['code'], 'register');
        $smsResult ?: $this->error("验证码错误");
        $insterData = [
            'phone' => $param['phone'],
            'name' => $param['name'],
            'grade' => $param['grade'],
            'create_time' => date("Y-m-d H:i:s"),
        ];
        $res = Db::name('onebyone')->insert($insterData);
        if ($res) {
            $this->success("已提交,请耐心等待工作人员与您联系");
        }
        $this->error('领取失败');
    }

    /**
     * Notes:根据课程id获取章节列表
     * User: XingLiangRen
     * Date: 2020/9/1
     * Time: 18:18
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getCourseLesson()
    {
        $id = $this->request->get('id');
        if (!Util::checkEmpty($id)) {
            $this->error("缺少参数");
        }
        $data = Db::name('course_lesson')->where(['course_id' => $id, 'lesson_status' => 1])->field('id,title')->select();
        $this->success('查询成功', $data);
    }

    /**
     * Notes:19 = 用户协议书 20 = 用户隐私协议 22 = 在线咨询(二维码)
     * User: XingLiangRen
     * Date: 2020/8/21
     * Time: 10:53
     */
    public function protocols()
    {
        $type = $this->request->get('type');
        if (!empty($type)) {
            $data = Db::name('config')->where('id', $type)->find();
        }
        empty($data) ? $this->error('非法参数') : $this->success('查询成功', $data);
    }

    /**
     * Notes:课程大纲
     * User: XingLiangRen
     * Date: 2020/8/26
     * Time: 17:40
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\Exception
     */
    public function getCourseOutline()
    {
        $id = input('id');
        if (!Util::checkEmpty($id)) {
            $this->error("缺少参数");
        }
        $data = Db::name('course')->where('id', $id)->field('tache,duration,expiry_start_time,expiry_end_time')->find();
        $courseLesson = Db::name('course_lesson')->alias('cl')
            ->join('course c', 'cl.course_id = c.id')
            ->join('teacher t', 'c.teacher_id = t.id')
            ->where(['course_id' => $id, 'lesson_status' => 1])
            ->field('cl.id,cl.lesson_id,cl.play_status,cl.play_status,cl.media_uri,t.nick_name,cl.title,cl.start_time,cl.end_time,cl.video_length')
            ->select();
        if (is_array($courseLesson)) {
            foreach ($courseLesson as $k => &$v) {
                $v['time'] = date('Y-m-d', strtotime($v['start_time'])) . ' ' . Util::weekday(strtotime($v['start_time'])) . ' ' . date('H:i', strtotime($v['start_time'])) . '-' . date('H:i', strtotime($v['end_time']));
                $userid = $this->auth->id;
                if (!empty($userid)) {
                    $v['learn'] = 0;
                    $res = Db::name('course_lesson_learn')->where('user_id', $this->getUid())->where('lesson_id', $v['id'])->where('status', 'finished')->find();
                    if ($res) {
                        $v['learn'] = 1;
                    }
                }
            }
        }
        $userid = $this->auth->id;
        if (!empty($userid)) {
            $lesson_id = \db('course_lesson_learn')->where(['user_id' => $this->getUid(), 'course_id' => $id])->max('lesson_id');
            $data['max_lesson_id'] = $lesson_id;
            if ($data['max_lesson_id'] == 0) {
                $lesson = Db::name('course_lesson')->where('course_id', $id)->order('lesson_id', 'ASC')->find();
                if (!empty($lesson)) {
                    $data['max_lesson_id'] = $lesson['id'];
                }
            }
            $studyNumber = Db::name('course_lesson_learn')->where(['user_id' => $this->getUid(), 'course_id' => $id])->count();
            $data['studyNumber'] = $studyNumber;
        }
        $data['count'] = count($courseLesson);
        $data['courseLesson'] = $courseLesson;
        $this->success('查询成功', $data);
    }

    /**
     * Notes:公司信息
     * User: XingLiangRen
     * Date: 2020/8/27
     * Time: 11:52
     */
    public function cityInfo()
    {
        $data = Db::name('config')->where(['id' => ['in', ['23', '24', '25', '26', '27', '29', '30', '31']]])->field('id,name,title,value')->select();
        $noob = Db::name('config')->where(['id' => ['in', ['29', '30', '31']]])->field('id,name,title,value')->select();
        $roleList = array_combine(array_column($data, 'name'), array_column($data, 'value'));
        $noobList = array_combine(array_column($noob, 'name'), array_column($noob, 'id'));
        $endData = array_merge($roleList, $noobList);
        $this->success('查询成功', $endData);
    }

    /**
     * Notes:查询新手指导详情
     * User: XingLiangRen
     * Date: 2020/8/28
     * Time: 11:34
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getNoobInfo()
    {
        $id = $this->request->get("id");
        if (!Util::checkEmpty($id)) {
            $this->error('缺少参数');
        }
        $data = Db::name('config')->where('id', $id)->field('name,title,value')->find();
        $this->success('查询成功', $data);
    }

    /**
     * Notes:banner列表
     * User: XingLiangRen
     * Date: 2020/8/28
     * Time: 11:34
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function myList()
    {
        $List = Db::name("banner")->where('status', '=', 'on')
            ->order("id desc")
            ->limit(0, 5)
            ->field('id,name,pic_url,link')
            ->select();
        $this->success("查询成功", $List);
    }
    public function myAdList()
    {
        $List = Db::name("ad")->where('status','=','on')
            ->order("id desc")->select();
        $this->success("ok",$List);
    }

    /**
     * Notes:课程类型列表
     * User: XingLiangRen
     * Date: 2020/8/28
     * Time: 11:35
     */
    public function classList()
    {
        $data = Db::name('classify')->select();
        $this->success('查询成功', $data);
    }

    /**
     * Notes:根据user_id获取studentID
     * User: XingLiangRen
     * Date: 2020/8/26
     * Time: 10:03
     */
    private function getUid()
    {
        return Db::name('student')->where('user_id', $this->auth->id)->field('id')->find()['id'];
    }
}